package com.ebupt.migu.music.userlist.controller;

import com.ebupt.migu.music.common.auth.AuthBaseUtils;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.entity.StaticUser;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.ReqestParamUtil;
import com.ebupt.migu.music.common.util.RestClientUtils;
import com.ebupt.migu.music.system.entity.SysUser;
import com.ebupt.migu.music.userlist.entity.UserBlackList;
import com.ebupt.migu.music.userlist.service.BlackListService;
import com.mysql.cj.util.StringUtils;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizm
 */
@RestController
@RequestMapping("/blacklist")
public class BlackListController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private BlackListService blService;
    @Autowired
    private RestClient restClient;
    // 文件默认保存路径
    @Value("${path.user_list_path}")
    private String FILE_UPLOAD_PATH;
    @Value("${spring.elasticsearch.alias}")
    private  String esIndex;
    @Value("${spring.elasticsearch.esType}")
    private  String esType;

    @RequestMapping("/checkBlackList")
    public ResultObject<Object> check() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        List<UserBlackList> list= blService.checkBlackList(paramMap);
        if(null!=list&&list.size()>0){
            retObj.setCode("0000");
            retObj.setMsg("黑名单中已存在该号码");
        }else{
            retObj.setCode("0001");
            retObj.setMsg("黑名单中不存在该号码");
        }
        return retObj;
    }

    @RequestMapping("/addBlackList")
    public ResultObject<Object> add() {
        // 获取用户登录信息
        SysUser user = AuthBaseUtils.getSessionUser(request);
        int insertNo=0;
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        paramMap.put("creatorId",null!=user?user.getLoginName():"");
        List<UserBlackList> list= blService.checkBlackList(paramMap);
        if(null!=list&&list.size()>0){
            retObj.setCode(StatusEnum.ADD_BLACKLIST_ERROR.getCode());
            retObj.setMsg("手动添加黑名单失败：黑名单中已存在该号码");
        }else{
            String msisdn= (String) paramMap.get("mobile");
            //es反查
            List<StaticUser> userList=RestClientUtils.getUser(restClient,msisdn,esIndex,esType);
            if(null!=userList&&userList.size()>0){
                for (int i = 0; i <userList.size() ; i++) {
                    StaticUser esUser=userList.get(i);
                    paramMap.put("uid",esUser.getUid());
                    paramMap.put("imei",esUser.getImei());
                    paramMap.put("idfa",esUser.getIdfa());
                    paramMap.put("blackId",System.currentTimeMillis());//时间戳，做排序用
                    paramMap.put("createTime",new Date());
                    Integer id = blService.addBlackList(paramMap);
                    if(null!=id){
                        insertNo++;
                    }else{
                        throw new MyException(StatusEnum.ADD_BLACKLIST_ERROR,StatusEnum.ADD_BLACKLIST_ERROR.getMsg());
                    }
                }
            }
            retObj.setData(null);
            retObj.setMsg("手动添加黑名单成功,条数："+insertNo);
        }
        return retObj;
    }

    @RequestMapping("/delBlackList")
    public ResultObject<Object> delete() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        Integer total =blService.delBlackList(paramMap);

        if(total>0){
            retObj.setData(total);
            retObj.setMsg("删除黑名单成功");
        }else{
            throw new MyException(StatusEnum.DEL_BLACKLIST_ERROR,StatusEnum.DEL_BLACKLIST_ERROR.getMsg());
        }
        return retObj;
    }
    @RequestMapping("/delBlackListBatch")
    public ResultObject<Object> deleteBatch() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        List<UserBlackList> list= blService.checkBlackList(paramMap);

        Integer total =blService.delBlackListBatch(paramMap);
        if(total>0){
            retObj.setData(total);
            retObj.setMsg("批量删除黑名单成功,个数："+total);
        }else{
            throw new MyException(StatusEnum.DEL_BLACKLIST_ERROR,StatusEnum.DEL_BLACKLIST_ERROR.getMsg());
        }
        return retObj;
    }
    @RequestMapping("/list")
    public ResultObject<Object> list() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        retObj.setMsg("查询黑名单列表成功");
        retObj.setData(blService.queryByPage(paramMap));
        return retObj;
    }

    @RequestMapping("/exportTemplate")
    public HttpServletResponse downloadDataTemplate() {
        //黑名单模板
        String fileName="blackListTemplate.csv";
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String realpath=classpath+"file/"+fileName;
        System.out.println(realpath);
        try {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=\""+ fileName+ "\"");
            request.setCharacterEncoding("UTF-8");
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(realpath);
            byte[] b = new byte[2048];
            int i = 0;

            while ((i = fis.read(b)) > 0) {
                os.write(b, 0, i);
            }

            fis.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 黑名单导入
     * @return
     */
    @PostMapping(value = "/csvImport")
    public ResultObject csvImport(@RequestParam("file") MultipartFile file){
        // 获取用户登录信息
         SysUser user = AuthBaseUtils.getSessionUser(request);
    	 ResultObject res = new ResultObject();
    	 // 校验文件是否为空，格式是否正常
         boolean isExcelFile = CSVUtils.validateUploadFile(file, "csv");
         if (!isExcelFile) {
             throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
         }
         Date date = new Date();
         String timeStr = DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
         String newPath=FILE_UPLOAD_PATH+timeStr+"_"+file.getOriginalFilename();
         //上传附件到指定目录
        //导入不需要保存附件，如果保存附件，因为流只能读取一次，那么csvRead要改用传上传文件path的方法
         CSVUtils.upload(file,newPath);
         //数据入库
         //List<String[]> data = CSVUtils.csvRead(file);
         List<String[]> data = CSVUtils.csvRead(newPath,',');
         int insertNumber=0;
         int skipNumber=0;
         if(null!=data&&data.size()>0) {
        	 for (int i = 1; i < data.size(); i++) {//跳过首行
        		   Map<String,Object> checkMap = new HashMap<String, Object>();
        		   checkMap.put("mobile", data.get(i)[1]);
        	        List<UserBlackList> list= blService.checkBlackList(checkMap);
        	        if(null!=list&&list.size()>0){//跳过白名单已存在行
        	        	skipNumber++;
        	        	continue;
        	        }else{
        	        	String mobile=data.get(i)[1];
        	        	if(StringUtils.isNullOrEmpty(mobile)) {//跳过手机号码为空行
        	        		skipNumber++;
        	        		continue;
        	        	}else {
        	        	 Map<String, Object> map = new HashMap<String, Object>();
        	        	 map.put("userName",data.get(i)[0]);
                         map.put("mobile",data.get(i)[1]);
                         map.put("remark",data.get(i)[2]);
                         map.put("creatorId",null!=user?user.getLoginName():"");
                         //es反查
                         List<StaticUser> userList=RestClientUtils.getUser(restClient,data.get(i)[1],esIndex,esType);
                            if(null!=userList&&userList.size()>0){
                                for (int j = 0; j <userList.size() ; j++) {
                                    StaticUser esUser=userList.get(j);
                                    map.put("uid",esUser.getUid());
                                    map.put("imei",esUser.getImei());
                                    map.put("idfa",esUser.getIdfa());
                                    map.put("blackId",System.currentTimeMillis());//时间戳，做排序用
                                    map.put("createTime",new Date());
                                    Integer id = blService.addBlackList(map);
                                    if(null!=id){
                                        insertNumber++;
                                    }else {
                                        throw new MyException(StatusEnum.ADD_BLACKLIST_ERROR,StatusEnum.ADD_BLACKLIST_ERROR.getMsg());
                                    }
                            }
                         }
        	        	}
        	        }     		
			}   	 
         }
         res.setMsg("导入成功条数："+insertNumber+",跳过条数："+skipNumber);
    	 return res;
    }
}

